// miniprogram/pages/writeNote/writeNote.js
const app = getApp();
var amapFile = require('../../lib/amap-wx.js');
var markersData = {
  latitude:'',
  longitude:'',
  key:"a53e2b35cf90ed37f1c97c99edf2cad2"
}

Page({

  /**
   * 页面的初始数据
   */
  data: {
    location:'',
    currentID:0,
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    tempFilePaths:[],
    tempCloudPaths:[],
    article:
      {},
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      currentID:options.currentID
    })
  },
  //删除图片
    onDeleteImg:function(e){
      var tapIndex = e.currentTarget.dataset.index;
      this.data.tempFilePaths.splice(tapIndex,1);
      this.setData({
        tempFilePaths:this.data.tempFilePaths
      });      
    },
    // 上传图片
    doUpload: function () {
      var that = this;
      // 选择图片
      wx.chooseImage({
        count: 9,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
          that.setData({
            tempFilePaths:res.tempFilePaths
          })
        },
        //
        fail: e => {
          console.error(e)
        }
      })
    },
    //用户点击允许获得信息权限
  getUserInfo(e) {
    //用户点击同意获得
    if(e.detail.userInfo){
      app.globalData.userInfo = e.detail.userInfo
      var that = this;
      this.onGetOpenid(function(){
        that.setData({
          openid:app.globalData.openid,
          userInfo: e.detail.userInfo,
          hasUserInfo: true
        })
      })
    }else{
      this.setData({
        hasUserInfo: false
      })
    }
  },
  getLocation(){
    wx.getLocation({
      altitude: 'altitude',
    })
  },
  bindFormSubmit(e){
    var that = this;
    console.log("release!")
    if(!e.detail.value.title){
      wx.showToast({
        icon:'none',
        title: '请输入标题'
      })
      return
    }

    var imgPaths=[];
    if(this.data.tempFilePaths.length==0){
      wx.showToast({
        icon:'none',
        title: '至少选择一张图片',
      })
      return
    }
    wx.showLoading({
      title: '发布中~',
    })
    const filePathsList = this.data.tempFilePaths
    var count = 0;
    for(var i = 0; i < filePathsList.length;i++){
        // 上传图片
        var filePath = filePathsList[i];
        const cloudPath = 'img/'+that.data.currentID+'/a'+that.data.currentID+'_'+i+`${filePathsList[i].match(/\.[^.]+?$/)[0]}`
        console.log(cloudPath);
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res) 
            count++;
            imgPaths.push(res.fileID);
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            that.getServerTime(function(){
              if(count == that.data.tempFilePaths.length){
                that.setData({
                  article:{
                    id:that.data.currentID,
                    imgPaths:imgPaths,
                    title:e.detail.value.title,
                    content:e.detail.value.content,
                    date:that.data.serverTime,
                    favorNum:0,
                    favorMembers:[],
                    comments:[],
                    location:that.data.location
                  }
                },function(){
                  that.addNoteToDataBase(that.data.article);
                  wx.hideLoading();
                })
              }
            })
          }
        })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  addNoteToDataBase: function (data) {
    const db = wx.cloud.database()
    db.collection('articles').add({
      data: {
        editor:this.data.userInfo.nickName,
        editor_avatarUrl:this.data.userInfo.avatarUrl,
        id:data.id,
        imgPaths:data.imgPaths,
        title:data.title,
        content:data.content,
        date:data.date,
        favorNum:data.favorNum,
        favorMembers:data.favorMembers,
        comments:data.comments,
        location:data.location
      },
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        wx.switchTab({
          url: '../index/index',
        })
        wx.showToast({
          title: '发布成功！',
        })
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '发布失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },
  getUserLocation:function(){
      var that = this;
      wx.getLocation({
        type: 'gcj02',
        success (res) {
          var latitude = res.latitude;
          var longtitude = res.longitude;
          console.log(res);
          that.loadCity(latitude,longtitude);
        },
      })
  },
  loadCity:function(lat,lon){
    var that = this;
    var myAmapFunction = new amapFile.AMapWX({key:markersData.key});
    myAmapFunction.getRegeo({
      location:''+lon+','+lat+'',
      success: function(data){
        console.log(data);
        var location =
        data[0].regeocodeData.formatted_address;
        that.setData({
          location:location
        })
      },
      fail:function(info){
        console.error(info);
      }
    })
  },

  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //如果用户已经授权,那么打开页面之后应该自动授权
    var that = this
    if(app.globalData.userInfo&&app.globalData.openid){
      this.setData({
        hasUserInfo:true,
        avatarUrl: app.globalData.userInfo.avatarUrl,
        userInfo: app.globalData.userInfo,
        openid:app.globalData.openid
      })
    }
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              that.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo,
                hasUserInfo:true
              })
              that.onGetOpenid(function(){
                app.globalData.userInfo = that.data.userInfo;
                app.globalData.avatarUrl = that.data.avatarUrl
              })
          }
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onGetOpenid: function(callback) {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        app.globalData.openid = res.result.openid
        callback();
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },
  getServerTime:function(callback){
    wx.cloud.callFunction({
      name: 'getdate',
      data: {},
      success: res => {
        this.setData({
          serverTime:res.result.localTime
        })
        callback();
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '获取服务器时间失败',
        })
        console.error('[云函数] [sum] 调用失败：', err)
      }
    })
  }
})